<?php
/**
 *（logic） 更新基础备货JP-sku提货（JP备货）
 */
namespace App\Logic\SsBasicJp;

use App\Models\Basics\SysArea;
use App\Models\Basics\SysPlat;
use App\Models\Basics\Transport;
use App\Models\Product\ProductSku;
use App\Models\SalesReport\DailyVolume;
use App\Models\SsBasic\JpSku;
use App\Models\SsBasic\JpSkuEstimate;
use App\Models\SsBasic\JpStockingSku;
use App\Models\Stocking\StockingSetDate;
use Illuminate\Support\Facades\DB;
class InitJpSS
{
    /**
     * 设定：每天运行 （jp:ss）
     */
    public static function exe(){
        try{
            $areaId = SysArea::AREA_JP; //JP站点
            $countryId = 12; //JP国家
            $setDateArr = [];
            $skuArr = [];
            $pCycle = [];
            $price = [];
            $transportDayArr = [];
            $classifyIdVolume7 = [];
            $classifyIdVolume30 = [];
            $time = strtotime('-1 days');
            JpStockingSku::query()
                ->orderBy('id')
                ->chunk(500, function ($countryStockingSkus) use (&$skuArr,&$pCycle,&$price,&$transportDayArr,&$setDateArr,&$classifyIdVolume7,&$classifyIdVolume30,$time,$areaId,$countryId){
                    DB::beginTransaction();
                    foreach ($countryStockingSkus as $stockingSku){
                        list($platId,$pSkuId) = explode('_',$stockingSku->area_psku);
                        $classifyId = ProductSku::getValueById($pSkuId,'classify_id') ?? 0;
                        $stockingSku->plat_id = $platId;
                        $stockingSku->area_id = $areaId;
                        $stockingSku->country_id = $countryId;
                        $stockingSku->psku_id = $pSkuId;
                        $stockingSku->classify_id = $classifyId;
                        if (!$stockingSku->save()) continue;

                        /**********推荐备货比例 start**********/
                        //系统推荐备货比例(7天)
                        $classifyNum7 = JpStockingSku::query()->where('plat_id',$platId)->where('classify_id',$classifyId)
                            ->sum('avg7');
                        $stockingSku->recommend_ratio7 = 0;
                        if (floatval($stockingSku->avg7) > 0 && floatval($classifyNum7) > 0) {
                            $stockingSku->recommend_ratio7 = round(floatval($stockingSku->avg7) / floatval($classifyNum7), 2) ?? 0;
                        }

                        //系统推荐备货比例(30天)
                        $classifyNum30 = JpStockingSku::query()->where('plat_id',$platId)->where('classify_id',$classifyId)
                            ->sum('avg30');
                        $stockingSku->recommend_ratio30 = 0;
                        if (floatval($stockingSku->avg30) > 0 && floatval($classifyNum30) > 0) {
                            $stockingSku->recommend_ratio30 = round(floatval($stockingSku->avg30) / floatval($classifyNum30), 2) ?? 0;
                        }
                        /**********推荐备货比例 end**********/

                        if(!array_key_exists($stockingSku->psku_id,$skuArr)){
                            $skuArr[$stockingSku->psku_id] = ProductSku::getModelById($stockingSku->psku_id);
                        }
                        $sku = $skuArr[$stockingSku->psku_id];
                        if(!array_key_exists($stockingSku->psku_id,$price)){
                            $price[$stockingSku->psku_id] = ProductSku::getPuPrice($sku);
                        }
                        if(!array_key_exists($stockingSku->psku_id,$pCycle)){
                            $pCycle[$stockingSku->psku_id] = ProductSku::getPuCycle($sku);
                        }
                        if(!array_key_exists($areaId,$transportDayArr)){
                            $_transportDay = Transport::getTransportDay($areaId);
                            $transportDayArr[$areaId] = $_transportDay ?: null;
                        }
                        $transportDay = $transportDayArr[$areaId];
                        if($transportDay){
                            $airDay = $transportDay->air_day;
                            $seaDay = $transportDay->sea_day;
                        }else{
                            $airDay = 0;
                            $seaDay = 0;
                        }
                        $estimate = JpSkuEstimate::query()->where('area_psku',$stockingSku->area_psku)->first();
                        for($i = 0;$i < JpSkuEstimate::ESTIMATE_NUM - 1;$i++){
                            $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
                            $stockingSku->{'estimate_num'.$i} = intval($num);
                        }
                        $stockingSku->unit_price = $price[$stockingSku->psku_id];
                        $stockingSku->purchase_cycle = $pCycle[$stockingSku->psku_id];
                        $stockingSku->air_day = $airDay;
                        $stockingSku->air_available = JpSku::getAvailable($stockingSku->purchase_cycle,$airDay);
                        $stockingSku->air_ship_factor = JpSku::getShipFactor($airDay);
                        $stockingSku->air_stock_factor = JpSku::getStockFactor($stockingSku->purchase_cycle,$airDay);
                        $stockingSku->sea_day = $seaDay;
                        $stockingSku->sea_available = JpSku::getAvailable($stockingSku->purchase_cycle,$seaDay);
                        $stockingSku->sea_ship_factor = JpSku::getShipFactor($seaDay);
                        $stockingSku->sea_stock_factor = JpSku::getStockFactor($stockingSku->purchase_cycle,$seaDay);
                        $setDateKey = $areaId.'_'.$sku->classify_id;
                        if(!array_key_exists($setDateKey,$setDateArr)){
                            $setDateArr[$setDateKey] = StockingSetDate::getSetDate($areaId,$sku->classify_id,$stockingSku->sea_available);
                        }
                        $stockingSku->set_date = $setDateArr[$setDateKey];
                        if($stockingSku->status == 4 || $stockingSku->status == 3){
                            $approvalTime = strtotime($stockingSku->approval_date);
                            if($approvalTime <= $time){
                                $stockingSku->apply_num = null;
                                $stockingSku->approval_num = null;
                                $stockingSku->approval_date = null;
                                $stockingSku->apply_remark = null;
                                $stockingSku->approval_remark = null;
                                $stockingSku->status = 1;
                                $stockingSku->seller_id = null;
                            }
                        }
                        $stockingSku->save();
                        $stockingSku->over_stock = JpStockingSku::getOverStock($stockingSku);
                        $stockingSku->over_stock_value = JpStockingSku::getOverStockValue($stockingSku->over_stock,$stockingSku->unit_price);
                        $stockingSku->save();
                    }
                    DB::commit();
                });

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
